package services

import (
	"restaurant-system/config"
	"restaurant-system/internal/models"
	"strings"
)

type AIService struct {
	config *models.AIServiceConfig
	rules  []models.AIQARule
}

func NewAIService() *AIService {
	var aiConfig models.AIServiceConfig
	if err := config.DB.First(&aiConfig).Error; err != nil {
		// 如果没有配置，创建默认配置
		aiConfig = models.AIServiceConfig{
			Enabled: true,
			Name:    "智能助手",
		}
		config.DB.Create(&aiConfig)
	}

	var rules []models.AIQARule
	config.DB.Order("priority desc").Find(&rules)

	return &AIService{
		config: &aiConfig,
		rules:  rules,
	}
}

// 处理用户消息
func (s *AIService) HandleMessage(sessionID uint, content string) *models.ChatMessage {
	if !s.config.Enabled {
		return nil
	}

	// 查找匹配的规则
	var answer string
	for _, rule := range s.rules {
		keywords := strings.Split(rule.Keywords, ",")
		for _, keyword := range keywords {
			if strings.Contains(content, strings.TrimSpace(keyword)) {
				answer = rule.Answer
				break
			}
		}
		if answer != "" {
			break
		}
	}

	// 如果没有匹配的规则，使用默认回复
	if answer == "" {
		answer = "您好，我是智能客服助手。您的问题已收到，稍后会有人工客服为您解答。"
	}

	// 创建AI回复消息
	message := &models.ChatMessage{
		SessionID:  sessionID,
		SenderID:   1, // AI的ID为0
		SenderType: "admin",
		Content:    answer,
		Type:       "text",
		Status:     "sent",
	}

	config.DB.Create(message)
	return message
}
